
package fileby.ctrl.actions.impl;

import fileby.core.ActionKey;
import fileby.core.IDisplayableFile;
import fileby.model.IFileManager;
import fileby.model.ISelectionManager;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.border.LineBorder;

/**
 *
 * @author Jacob
 */
class RenameAction extends AbstractAction {

    private IFileManager fileManager;
    private ISelectionManager selectionManager;
    private JTextField textField;
    private JPanel glassPane;
    private IDisplayableFile file;

     public RenameAction(IFileManager fileManager, ISelectionManager selectionManager) {
        super("Rename", null);
        this.fileManager = fileManager;
        this.selectionManager = selectionManager;
        putValue(SHORT_DESCRIPTION, "Rename selected file");
        putValue(MNEMONIC_KEY, KeyEvent.VK_R);
        putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_DOWN_MASK));
    }

    public void actionPerformed(ActionEvent e) {
        textField = (JTextField)getValue(ActionKey.RENAME.toString());
        glassPane = (JPanel)getValue("GlassPane");
        file = (IDisplayableFile)getValue("File");
        showTextField();
        initTextFieldCtrl();
    }

    private void hideTextField() {
        textField.setEditable(false);
        textField.setBorder(null);
        textField.setOpaque(false);
        glassPane.setVisible(true);
    }

    private void showTextField() {
        glassPane.setVisible(false);
        textField.setEditable(true);
        textField.setBorder(new LineBorder(Color.BLACK));
        textField.setBackground(Color.WHITE);
        textField.setOpaque(true);
        textField.requestFocusInWindow();
        textField.selectAll();
    }

    private void initTextFieldCtrl () {
        AbstractAction action = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                rename();
            }
        };
        action.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
        textField.setAction(action);
        textField.addFocusListener(new FocusListener() {
            public void focusGained(FocusEvent e) {}
            public void focusLost(FocusEvent e) {
                hideTextField();
            }
        });
    }

    private void rename() {
        hideTextField();
        String oldName = file.getAbsolutePath();
        String newName = file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("\\") + 1) + textField.getText();
        fileManager.rename(oldName, newName);
        selectionManager.setSingleSelected(newName);
    }

}
